/**
 * 当天选车次列表
 * @email 626097912@qq.com
 * Created by dength on 2017/04/18
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    ScrollView,
    ListView,
    RefreshControl,
    InteractionManager
} from 'react-native';
import BaseComponent from '../base/baseComponent';
import Constants from '../base/constants';
import * as urls from '../base/constants_url';
import CommonStyles from '../base/commonStyles';
import Loading from '../components/Loading';
import Icon from 'react-native-vector-icons/Entypo';
import store from 'react-native-simple-store';
import { getNavigator } from '../route/route';

class RtrainList extends BaseComponent {
    constructor(props) {
        super(props);
        this._renderRow = this._renderRow.bind(this);
        this.fetchData = this.fetchData.bind(this);
        this.state = {
            isLoading: true,
            cfCity: '',
            zdCity: '',
            cfDate: '',
            InitialWeek: '',//顶栏星期
            InitialDate: '',//顶栏日期
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            })
        };
    }

    getNavigationBarProps() {
        let { cfCity, zdCity} = this.state;
        return {
            title: cfCity + "－" + zdCity,
            leftButtonImage: require('../images/ic_return.png'),
            hideRightButton: true,
        };
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(this.fetchData);
        store.get('TrainIndex')
            .then(TrainIndex => {
                this.setState({
                    cfCity: TrainIndex.Thefirst,
                    zdCity: TrainIndex.End,
                    cfDate: TrainIndex.selectedDate
                });
                let InitializationDate = Date.parse(new Date(TrainIndex.selectedDate)) / 1000;
                var formatDate = this._timetrans(InitializationDate);
                switch (new Date(TrainIndex.selectedDate).getDay()) {
                    case 0: InitialWeek = "星期天"; break
                    case 1: InitialWeek = "星期一"; break
                    case 2: InitialWeek = "星期二"; break
                    case 3: InitialWeek = "星期三"; break
                    case 4: InitialWeek = "星期四"; break
                    case 5: InitialWeek = "星期五"; break
                    case 6: InitialWeek = "星期六"; break
                }
                this.setState({
                    InitialWeek: InitialWeek,
                    InitialDate: formatDate
                });
            });
    }

    fetchData() {
        const { dataSource} = this.props;
        let { cfCity, zdCity, cfDate} = this.state;
        let param = 'fromStation=' + cfCity + '&toStation=' + zdCity + '&startDate=' + cfDate
        fetch(urls.queryTrain, {
            method: 'POST',
            headers: {
                'Host': 'http://thisa',
                'Referer': 'http://thisa',
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: param
        })
            .then((response) => response.json()) //把response转为json
            .then((responseData) => { // 上面的转好的json
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(responseData.data),
                    isLoading: false,
                });
            })
            .catch((error) => {
                alert('错误:' + error);
                this.setState({
                    isLoading: false,
                });
            })
    }

    //格式化时间
    _timetrans(date) {
        var date = new Date(date * 1000);//如果date为10位不需要乘1000
        var Y = date.getFullYear() + '年';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日';
        return M + D;
    }

    _onPress(navname) {
        getNavigator().push({ name: navname });
    }

    //渲染每一项的数据
    _renderRow(rowData) {
        const { values} = this.props;
        return (
            <TouchableOpacity
                activeOpacity={0.8}
                //onPress={() => this._onPress('FixedSeat')}
                style={styles.list_box}>
                <View style={styles.list_middle}>
                    <View style={styles.list_li}>
                        <View style={styles.list_li_lf}>
                            <Image style={styles.dateselection_ce_img} source={require('../images/ic_rtrainList_s.png')} />
                        </View>
                        <View style={styles.startingStation}>
                            <View style={styles.ss_textbox}>
                                <Text style={styles.ss_textbox_tx}>
                                    {rowData.queryLeftNewDTO.from_station_name}
                                </Text>
                                <View style={styles.ss_textbox_tx_po}>
                                    <Text style={{ fontSize: 12, color: '#989898' }}>
                                        {rowData.queryLeftNewDTO.start_time}
                                    </Text>
                                </View>
                            </View>
                            <View style={styles.checi}>
                                <View style={styles.checi_xian}></View>
                                <View style={styles.checi_xian_top}>
                                    <Text style={[styles.checi_xian_tx, { fontWeight: 'bold' }]}>
                                        {rowData.queryLeftNewDTO.station_train_code}
                                    </Text>
                                </View>
                                <View style={styles.checi_xian_bt}>
                                    <Text style={styles.checi_xian_tx}>
                                        {rowData.queryLeftNewDTO.lishi}
                                    </Text>
                                </View>
                            </View>
                            <View style={styles.ss_textbox}>
                                <Text style={styles.ss_textbox_tx}>
                                    {rowData.queryLeftNewDTO.to_station_name}
                                </Text>
                                <View style={styles.ss_textbox_tx_po}>
                                    <Text style={{ fontSize: 12, color: '#989898' }}>
                                        {rowData.queryLeftNewDTO.arrive_time}
                                    </Text>
                                </View>
                            </View>
                        </View>
                        <View style={styles.list_li_rg}>
                            <Image style={styles.dateselection_ce_img} source={require('../images/ic_rtrainList_z.png')} />
                        </View>
                    </View>
                    <View style={styles.yupiao}>
                        <View style={styles.yupiao_box}>
                            <View style={styles.yupiao_li}>
                                <Text style={styles.yupiao_li_tx}>
                                    {values ? '商务座:' : '软卧:'}
                                    <Text>{values ? rowData.queryLeftNewDTO.swz_num : rowData.queryLeftNewDTO.rw_num}</Text>
                                </Text>
                            </View>
                            <View style={styles.yupiao_li}>
                                <Text style={styles.yupiao_li_tx}>
                                    {values ? '特等座:' : '硬卧:'}
                                    <Text>{values ? rowData.queryLeftNewDTO.tz_num : rowData.queryLeftNewDTO.yw_num}</Text>
                                </Text>
                            </View>
                            <View style={styles.yupiao_li}>
                                <Text style={styles.yupiao_li_tx}>
                                    {values ? '一等座:' : '软座:'}
                                    <Text>{values ? rowData.queryLeftNewDTO.zy_num : rowData.queryLeftNewDTO.rz_num}</Text>
                                </Text>
                            </View>
                            <View style={styles.yupiao_li}>
                                <Text style={styles.yupiao_li_tx}>
                                    {values ? '二等座:' : '硬座:'}
                                    <Text>{values ? rowData.queryLeftNewDTO.ze_num : rowData.queryLeftNewDTO.yz_num}</Text>
                                </Text>
                            </View>
                            <View style={styles.yupiao_li}>
                                <Text style={styles.yupiao_li_tx}>
                                    无座:
                            <Text>{values ? rowData.queryLeftNewDTO.wz_num : rowData.queryLeftNewDTO.wz_num}</Text>
                                </Text>
                            </View>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    //选择日期
    _ReSelectionDate() {
        getNavigator().push({
            name: 'DepartureDate',
            pages:1
        })
    }


    renderBody() {
        let {dataSource, isLoading, InitialWeek, InitialDate} = this.state;
        if (!isLoading) {
            return (
                <View style={styles.container}>

                    <View style={styles.dateselection}>
                        <View style={styles.dateselection_box}>
                            <TouchableOpacity
                                activeOpacity={0.8}
                                style={styles.dateselection_lr}
                                >
                                <Icon name="chevron-small-left" size={26} color="#ffffff" />
                            </TouchableOpacity>
                            <TouchableOpacity
                                activeOpacity={0.8}
                                onPress={() => this._ReSelectionDate()}
                                style={styles.dateselection_ce}>
                                <Image style={styles.dateselection_ce_img} source={require('../images/ic_rtrainList_t.png')} />
                                <Text style={styles.dateselection_ce_tx}>{InitialDate}</Text>
                                <Text style={{ color: 'white', fontSize: 12 }}>
                                    {InitialWeek}
                                    {/*(
                                <Text>今天</Text>
                                    )*/}
                                </Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                activeOpacity={0.8}
                                style={styles.dateselection_lr}
                                >
                                <Icon name="chevron-small-right" size={26} color="#ffffff" />
                            </TouchableOpacity>
                        </View>
                    </View>
                    <ScrollView showsVerticalScrollIndicator={false}>
                        <View style={{ margin: 8, marginTop: 0 }}>

                            <ListView
                                //initialListSize={5}  
                                dataSource={dataSource}
                                renderRow={this._renderRow}
                                onEndReachedThreshold={10}
                                //renderSeparator={this._renderSeparatorView}
                                />
                        </View>
                    </ScrollView>
                </View>

            );
        }
        return (
            <Loading isShow={this.state.isLoading} />
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: CommonStyles.colors.background,
    },
    dateselection: {
        backgroundColor: '#FF6600', width: Constants.window.width, height: 44,
    },
    dateselection_box: {
        marginLeft: 18, marginRight: 18, width: Constants.window.width - 36, flexDirection: 'row', height: 44, justifyContent: 'center'
    },
    dateselection_lr: {
        width: 30, justifyContent: 'center', height: 44
    },
    dateselection_ce: {
        width: (Constants.window.width - 36) - 60, justifyContent: 'center', flexDirection: 'row', alignItems: 'center'
    },
    dateselection_ce_img: {
        width: 17, height: 18
    },
    dateselection_ce_tx: {
        color: 'white', fontSize: 12, paddingRight: 10, paddingLeft: 8
    },
    list_box: {
        backgroundColor: CommonStyles.colors.white, width: Constants.window.width - 16,
        borderRadius: 10, height: 80, marginTop: 8
    },
    list_middle: {
        margin: 6, width: (Constants.window.width - 16) - 12, height: 80 - 16
    },
    list_li: {
        height: 38, justifyContent: 'center', flexDirection: 'row'
    },
    list_li_lf: {
        height: 38, justifyContent: 'center', width: 30, alignItems: 'flex-start'
    },
    list_li_rg: {
        height: 38, justifyContent: 'center', width: 30, alignItems: 'flex-end'
    },
    startingStation: {
        width: ((Constants.window.width - 16) - 12) - 60, flexDirection: 'row'
    },
    ss_textbox: {
        justifyContent: 'center', width: 60, alignItems: 'center',
    },
    ss_textbox_tx: {
        fontSize: 14, fontWeight: 'bold'
    },
    ss_textbox_tx_po: {
        position: 'absolute', bottom: -4, left: 15
    },
    checi: {
        width: (((Constants.window.width - 16) - 12) - 60) - 120, justifyContent: 'center', alignItems: 'center',
    },
    checi_xian: {
        width: (((Constants.window.width - 16) - 12) - 60) - 140, height: 1, backgroundColor: '#989898'
    },
    checi_xian_top: {
        width: 60, position: 'absolute', top: 0,
        left: ((((Constants.window.width - 16) - 12) - 60) - 140 - 60) / 2 + 10, alignItems: 'center'
    },
    checi_xian_tx: {
        fontSize: 12, color: '#989898'
    },
    checi_xian_bt: {
        width: 60, position: 'absolute', bottom: 0,
        left: ((((Constants.window.width - 16) - 12) - 60) - 140 - 60) / 2 + 10, alignItems: 'center'
    },
    yupiao: {
        height: 15, marginTop: 80 - 16 - 38 - 15, flexDirection: 'row', justifyContent: 'center'
    },
    yupiao_box: {
        width: (Constants.window.width - 16) - 12, flexDirection: 'row'
    },
    yupiao_li: {
        width: ((Constants.window.width - 16) - 12) / 5, alignItems: 'flex-start'
    },
    yupiao_li_tx: {
        fontSize: 10, color: '#989898'
    },
});

export default RtrainList;